var FilePath=require("../file-path.js")
let fs = require('fs');
let AppData = require(FilePath.Objects+'common-data.js').AppData;
var Util=require(FilePath.ModulesPath+"util.js")
var multer  = require('multer');
var upload = multer({dest: 'upload_tmp/'});
var express=require('express');
var router = express.Router();   /*可使用 express.Router 类创建模块化、可挂载的路由句柄*/
var bodyParser = require('body-parser');
router.use(bodyParser.urlencoded({ extended: false }));
router.use(bodyParser.json());

router.get('/',async function(req,res){
    let state = "正常状态"
    if (fs.existsSync(AppData.GetUpgradeFileName())) {
        state = "可以升级状态";
    }
    res.render('engine',{
        list:{VersionState:state}
    });
})

router.post('/upgradeEngine',upload.any(),async function(req,res){
    if(!req.files[0].originalname){
        res.redirect('/engine');
    }else{
        let des_file = AppData.GetUpgradeFileDir() + req.files[0].originalname;
        console.log("MSG: Get file",des_file)
        fs.readFile( req.files[0].path, function (err, data) {
            fs.writeFile(des_file, data, function (err) {
                if( err ){
                    console.log( err );
                }else{
                    res.redirect('/engine');
                }
            });
        });
    }
})

router.get('/delUpgradeZip',async function(req,res){
    console.log("MSG: rm ",AppData.GetUpgradeFileDir())
    try{
        await Util.SyncRunCmd(AppData.GetDelUpgradFileCmd());
    }catch{

    }
    res.redirect('/engine');
})

router.get('/engineReboot',async function(req,res){
    res.redirect('/engine');
    await Util.SyncRunCmd(AppData.GetEngineRebootCmd());  //放到重定向后面
})
module.exports = router;
